package com.landeb.shop.huo.frag;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Toast;

import com.landeb.shop.R;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.act.OrderDetailActivity;
import com.landeb.shop.huo.act.ShopsCollectionActivity;
import com.landeb.shop.huo.adapter.AllOrderFragLVAdapter;
import com.landeb.shop.huo.bean.BeanOrderFrag;
import com.landeb.shop.huo.httpRequest.FragOrderRequest;
import com.landeb.shop.huo.view.FootView;
import com.landeb.shop.huo.view.OrderListview;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class OrderFragment extends Fragment {
    private static final String BASE_URL = "baseUrl";

    private String mBaseUrl;

    private String mStatus;
    private String is_comment;

    private View view;

    private OrderListview mOrderListview;
    private List<BeanOrderFrag.DataBean.ListBean> mList;
    private AllOrderFragLVAdapter mAdapter;
    private FootView mFootView;


    private String mUrl;
    private Retrofit mRetrofit;
    private FragOrderRequest mRequest;

    private int page = 0;
    private boolean hasNextPage = true;
    private boolean isLoading = false;
    private boolean isRefreshing = false;

    private boolean isViewPrepared = false; // 标识fragment视图已经初始化完毕
    private boolean hasFetchData = false; // 标识已经触发过懒加载数据

    public OrderFragment() {
        // Required empty public constructor
    }


    public static OrderFragment newInstance(String baseUrl) {
        OrderFragment fragment = new OrderFragment();
        Bundle args = new Bundle();
        args.putString(BASE_URL, baseUrl);
        fragment.setArguments(args);
        return fragment;
    }

    public static OrderFragment newInstance(String baseUrl, String status, String is_comment) {
        OrderFragment fragment = new OrderFragment();
        Bundle args = new Bundle();
        args.putString(BASE_URL, baseUrl);
        args.putString("status", status);
        args.putString("is_comment", status);

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mBaseUrl = getArguments().getString(BASE_URL);
            mStatus = getArguments().getString("status");
            is_comment = getArguments().getString("is_comment");

        }


        OkHttpClient client = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mRequest = mRetrofit.create(FragOrderRequest.class);


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_order, container, false);


        initView();
        initData();
        initEvent();

        isViewPrepared = true;

        if (!hasFetchData && getUserVisibleHint()) {
            refresh();
        }
        return view;
    }

    public void refresh() {

        page = 1;
        hasNextPage = true;

        if (!isRefreshing) {

            isRefreshing = true;

            mRequest.getOrder(page, 10, mStatus, is_comment)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanOrderFrag>() {
                        @Override
                        public void onCompleted() {

                            Log.e("getOrder", "onCompleted: ");
                            isRefreshing = false;
                            hasFetchData = true;
                        }

                        @Override
                        public void onError(Throwable e) {

                            Log.e("getOrder", "onError: " + e.toString());
                            isRefreshing = false;

                        }

                        @Override
                        public void onNext(BeanOrderFrag beanOrderFrag) {

                            if (beanOrderFrag.getStatus() == 1) {

                                mList.clear();
                                mList.addAll(beanOrderFrag.getData().getList());
                                mAdapter.notifyDataSetChanged();
//                                mOrderListview.smoothScrollToPosition(0);
                                mOrderListview.setSelection(0);

                                if (beanOrderFrag.getData().getMore() == 1) {
                                    hasNextPage = true;
                                    mFootView.setToRefresh();
                                } else {
                                    hasNextPage = false;
                                    mFootView.setFinished();
                                }

                            } else {
                                Toast.makeText(getContext(), beanOrderFrag.getInfo(), Toast.LENGTH_SHORT).show();
                            }

                        }
                    });

        }
    }

    private void loadMore() {


        page++;

        if (!isLoading && hasNextPage) {

            isLoading = true;
            mFootView.setRefreshing();

            mRequest.getOrder(page, 10, mStatus, is_comment)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanOrderFrag>() {
                        @Override
                        public void onCompleted() {

                            Log.e("getOrder", "onCompleted: ");
                            isLoading = false;

                        }

                        @Override
                        public void onError(Throwable e) {

                            Log.e("getOrder", "onError: " + e.toString());
                            isLoading = false;

                        }

                        @Override
                        public void onNext(BeanOrderFrag beanOrderFrag) {

                            if (beanOrderFrag.getStatus() == 1) {

                                mList.addAll(beanOrderFrag.getData().getList());
                                mAdapter.notifyDataSetChanged();

                                if (beanOrderFrag.getData().getMore() == 1) {
                                    hasNextPage = true;
                                    mFootView.setToRefresh();
                                } else {
                                    hasNextPage = false;
                                    mFootView.setFinished();
                                }

                            } else {
                                Toast.makeText(getContext(), beanOrderFrag.getInfo(), Toast.LENGTH_SHORT).show();
                            }

                        }
                    });

        }

    }

    private void initEvent() {

        mAdapter = new AllOrderFragLVAdapter(getContext(), mList,mRequest,this);
        mOrderListview.setAdapter(mAdapter);

        mOrderListview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

                if (i == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        loadMore();

                    }
                }

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });

        mOrderListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                // TODO: 2016/11/12 单击事件
                OrderDetailActivity.toAct(getContext(), mList.get(i).getId());
//                Toast.makeText(getContext(), mList.get(i).getId(), Toast.LENGTH_SHORT).show();

            }
        });

    }

    private void initData() {

        mList = new ArrayList<>();


    }

    private void initView() {

        mOrderListview = (OrderListview) view.findViewById(R.id.orderLV_order_frag);
        mFootView = new FootView(getContext());
        mOrderListview.addFooterView(mFootView, null, false);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser && isViewPrepared) {
            refresh();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isViewPrepared = false;
    }
}
